const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3000/api';
const JWT_TOKEN = 'your_jwt_token_here'; // 替换为实际的JWT token

// 设置请求头
const headers = {
  'Authorization': `Bearer ${JWT_TOKEN}`,
  'Content-Type': 'application/json'
};

// 测试新的订单流程
async function testNewOrderFlow() {
  try {
    console.log('🚀 开始测试新的订单流程...\n');
    
    if (JWT_TOKEN === 'your_jwt_token_here') {
      console.log('⚠️  请先设置有效的JWT token');
      console.log('   在脚本中修改 JWT_TOKEN 变量的值\n');
      return;
    }

    const shortsId = 1;
    const chapterId = 2;

    // 1. 先尝试获取视频URL（应该失败，因为没有订单）
    console.log('1️⃣ 测试获取视频URL（无订单状态）...');
    try {
      const videoResponse = await axios.get(
        `${BASE_URL}/shorts/chapter/video/${shortsId}/${chapterId}`,
        { headers }
      );
      
      console.log('✅ 获取视频URL成功:', JSON.stringify(videoResponse.data, null, 2));
      
      if (videoResponse.data.videoUrl) {
        console.log('🎉 有订单，可以直接观看！');
        console.log(`   视频URL: ${videoResponse.data.videoUrl}`);
        console.log(`   订单信息: ${JSON.stringify(videoResponse.data.orderInfo)}`);
      } else {
        console.log('📝 无订单，需要先购买');
        console.log(`   提示信息: ${videoResponse.data.message}`);
        console.log(`   有效积分: ${videoResponse.data.effectivePoints}`);
      }
      
    } catch (error) {
      console.log('❌ 获取视频URL失败:', error.response?.data?.message || error.message);
    }

    console.log('\n' + '─'.repeat(50));

    // 2. 创建订单
    console.log('2️⃣ 测试创建短剧订单...');
    try {
      const orderResponse = await axios.post(
        `${BASE_URL}/shorts/order`,
        {
          shortsId: shortsId,
          chapterIds: [chapterId]
        },
        { headers }
      );
      
      console.log('✅ 创建订单成功:', JSON.stringify(orderResponse.data, null, 2));
      
      const orderData = orderResponse.data;
      console.log(`💎 总积分: ${orderData.totalPoints}`);
      console.log(`📋 订单数量: ${orderData.orders.length}`);
      console.log(`👑 VIP用户: ${orderData.isVip ? '是' : '否'}`);
      console.log(`💬 消息: ${orderData.message}`);
      
      // 显示每个订单的详细信息
      orderData.orders.forEach((order, index) => {
        console.log(`\n   订单${index + 1}:`);
        console.log(`     ID: ${order.orderId}`);
        console.log(`     章节ID: ${order.chapterId}`);
        console.log(`     积分: ${order.points}`);
        console.log(`     状态: ${order.status}`);
        console.log(`     创建时间: ${new Date(order.createdAt).toLocaleString()}`);
      });
      
    } catch (error) {
      console.log('❌ 创建订单失败:', error.response?.data?.message || error.message);
      
      if (error.response?.status === 400) {
        console.log('💡 提示: 可能该章节已购买或参数错误');
      } else if (error.response?.status === 403) {
        console.log('💡 提示: 积分不足');
      }
    }

    console.log('\n' + '─'.repeat(50));

    // 3. 再次尝试获取视频URL（应该成功，因为已有订单）
    console.log('3️⃣ 测试获取视频URL（有订单状态）...');
    try {
      const videoResponse2 = await axios.get(
        `${BASE_URL}/shorts/chapter/video/${shortsId}/${chapterId}`,
        { headers }
      );
      
      console.log('✅ 获取视频URL成功:', JSON.stringify(videoResponse2.data, null, 2));
      
      if (videoResponse2.data.videoUrl) {
        console.log('🎉 有订单，可以观看！');
        console.log(`   视频URL: ${videoResponse2.data.videoUrl}`);
        console.log(`   订单信息: ${JSON.stringify(videoResponse2.data.orderInfo)}`);
        console.log(`   消息: ${videoResponse2.data.message}`);
      } else {
        console.log('📝 仍然无订单');
        console.log(`   提示信息: ${videoResponse2.data.message}`);
      }
      
    } catch (error) {
      console.log('❌ 获取视频URL失败:', error.response?.data?.message || error.message);
    }

    console.log('\n' + '─'.repeat(50));

    // 4. 测试批量购买（购买整个短剧）
    console.log('4️⃣ 测试批量购买整个短剧...');
    try {
      const batchOrderResponse = await axios.post(
        `${BASE_URL}/shorts/order`,
        {
          shortsId: shortsId
          // 不传chapterIds，购买整个短剧
        },
        { headers }
      );
      
      console.log('✅ 批量购买成功:', JSON.stringify(batchOrderResponse.data, null, 2));
      
      const batchData = batchOrderResponse.data;
      console.log(`💎 总积分: ${batchData.totalPoints}`);
      console.log(`📋 订单数量: ${batchData.orders.length}`);
      console.log(`👑 VIP用户: ${batchData.isVip ? '是' : '否'}`);
      console.log(`💬 消息: ${batchData.message}`);
      
    } catch (error) {
      console.log('❌ 批量购买失败:', error.response?.data?.message || error.message);
      
      if (error.response?.status === 400) {
        console.log('💡 提示: 可能部分章节已购买');
      }
    }

    console.log('\n✨ 新订单流程测试完成！');
    console.log('\n💡 测试要点:');
    console.log('   - 获取视频URL接口只检查订单，不自动创建');
    console.log('   - 需要先调用创建订单接口');
    console.log('   - 支持单个或多个章节购买');
    console.log('   - VIP用户扣除0积分');
    console.log('   - 普通用户扣除原积分');
    console.log('   - 订单创建后可以正常获取视频URL');

  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error.message);
  }
}

// 运行测试
testNewOrderFlow().catch(console.error); 